package com.josty.qualifying.adapters

import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView


class CustomLayoutManager(private val orientation: String): RecyclerView.LayoutManager() {
    private var scroll = true
    val VERTICAL = "VERTICAL"
    val HORIZONTAL = "HORIZONTAL"

    override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams {
        return RecyclerView.LayoutParams(
            RecyclerView.LayoutParams.MATCH_PARENT,
            RecyclerView.LayoutParams.MATCH_PARENT
        )
    }

    override fun canScrollHorizontally() = scroll && orientation == HORIZONTAL
    override fun canScrollVertically() = scroll && orientation == VERTICAL

    override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State) {
        fillDown(recycler)
    }

    private fun fillDown(recycler: RecyclerView.Recycler){

        var pos = 0
        var fillDown = true
        val height = height
        var viewTop = 0
        val itemCount = itemCount
        val widthSpec: Int = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY)
        val heightSpec: Int =
            View.MeasureSpec.makeMeasureSpec(getHeight(), View.MeasureSpec.EXACTLY)

        while (fillDown && pos < itemCount) {
            val view: View = recycler.getViewForPosition(pos)
            addView(view)
            measureChildWithDecorationsAndMargin(view, widthSpec, heightSpec)
            val decoratedMeasuredWidth = getDecoratedMeasuredWidth(view)
            layoutDecorated(view, 0, viewTop, decoratedMeasuredWidth, viewTop + view.height)
            viewTop = getDecoratedBottom(view)
            fillDown = viewTop <= height
            pos++
        }
    }

    private fun measureChildWithDecorationsAndMargin(child: View, wSpec: Int, hSpec: Int) {
        var widthSpec = wSpec
        var heightSpec = hSpec
        val decorRect = Rect()
        calculateItemDecorationsForChild(child, decorRect)
        val lp = child.layoutParams as RecyclerView.LayoutParams
        widthSpec = updateSpecWithExtra(
            widthSpec, lp.leftMargin + decorRect.left,
            lp.rightMargin + decorRect.right
        )
        heightSpec = updateSpecWithExtra(
            heightSpec, lp.topMargin + decorRect.top,
            lp.bottomMargin + decorRect.bottom
        )
        child.measure(widthSpec, heightSpec)
    }

    private fun updateSpecWithExtra(spec: Int, startInset: Int, endInset: Int): Int {
        if (startInset == 0 && endInset == 0) {
            return spec
        }
        val mode = View.MeasureSpec.getMode(spec)
        return if (mode == View.MeasureSpec.AT_MOST || mode == View.MeasureSpec.EXACTLY) {
            View.MeasureSpec.makeMeasureSpec(
                View.MeasureSpec.getSize(spec) - startInset - endInset, mode
            )
        } else spec
    }
}